//
//  XASectionPageView.swift
//  XAPageViewDemo
//
//  Created by XangAm on 2018/1/3.
//  Copyright © 2018年 Lan. All rights reserved.
//

import UIKit


protocol XASectionPageViewDelegate : class{
    func sectionPageView(_ sectionPageView : XASectionPageView,selectedIndex : Int) ->Void
}


class XASectionPageView: UIView {
    internal var pageViewDataSource : XAPageViewDataSource?
    internal var pageViewDelegate   : XAPageViewDelegate?
    internal var sectionPageViewDelegate   : XASectionPageViewDelegate?
    fileprivate var sectionPageLayout : XASectionPageLayout!
    fileprivate var currentSection         : Int = -1
    fileprivate lazy var collectionView    : UICollectionView = {
        let collectionView : UICollectionView = UICollectionView(frame: bounds, collectionViewLayout: sectionPageLayout)
        collectionView.bounces         = false
        collectionView.isPagingEnabled = true
        collectionView.delegate   = self
        collectionView.dataSource = self
        collectionView.showsHorizontalScrollIndicator = false
        return collectionView
    }()
    fileprivate lazy var sectionPageControl : UIPageControl! = {
        let frame  = CGRect(x: 0, y: bounds.height - 20, width: 50,height:20)
        let pageControl = UIPageControl()
        pageControl.frame.origin.y = bounds.height - 20
        pageControl.center.x       = center.x
        pageControl.pageIndicatorTintColor = UIColor.white
        pageControl.currentPageIndicatorTintColor = UIColor.red
        pageControl.isEnabled = false
        pageControl.numberOfPages = 2
        pageControl.currentPage   = 1
        return pageControl
    }()
    
   
  
    init(frame: CGRect ,layout : XASectionPageLayout,dataSource : XAPageViewDataSource?,delegate : XAPageViewDelegate?) {
        self.sectionPageLayout = layout
        self.pageViewDataSource = dataSource
        self.pageViewDelegate   = delegate
        super.init(frame: frame)
        setupSubviews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: - Setup
extension XASectionPageView {
    fileprivate func setupSubviews(){
        addSubview(collectionView)
    
        //init pageControl
        addSubview(sectionPageControl)
        
        DispatchQueue.main.async {
            self.dealSubviewsStatus(sectionChange: nil)
        }
       
    }
}

//MARK: - Open
extension XASectionPageView {
    open func register(_ cellClass: Swift.AnyClass?, forCellWithReuseIdentifier identifier: String){
        collectionView.register(cellClass, forCellWithReuseIdentifier: identifier)
        
    }
    open func register(_ nib: UINib?, forCellWithReuseIdentifier identifier: String){
        
        collectionView.register(nib, forCellWithReuseIdentifier: identifier)
    }
    open func dequeueReusableCell(withReuseIdentifier identifier: String, for indexPath: IndexPath) -> UICollectionViewCell{
       return collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
    }
}


//MARK: - Deal
extension XASectionPageView {
    fileprivate func dealScrollDidEnd(){
        dealSubviewsStatus(){
            (index) in
            self.sectionPageViewDelegate?.sectionPageView(self, selectedIndex:index)
        }
        
        
    }
    
    fileprivate func dealSubviewsStatus(sectionChange : ((_ sectionIndex : Int)->Void)?){
        guard let pageViewDataSource = pageViewDataSource else {
            return
        }
        //        let currentPage = collectionView.contentOffset.x / bounds.width
        let indexPoint = CGPoint(x: collectionView.contentOffset.x + sectionPageLayout.sectionInset.left + 1.0, y: sectionPageLayout.sectionInset.top + 1.0)
        let indexPath    = collectionView.indexPathForItem(at: indexPoint)
        guard let desIndexPath = indexPath else {
            return
        }
        //计算section里的currentPage和numberOfPages
        let pageCount = sectionPageLayout.cols * sectionPageLayout.rows//一页最多有多少Item
        let sectionPageIndex = desIndexPath.item / pageCount
        sectionPageControl.currentPage = sectionPageIndex
        //当组发生改变的时候,重新计算numberOfPages
        if currentSection != desIndexPath.section{
            let itemCount  = pageViewDataSource.pageView!(superview as! XAPageView, onSectionPageNumOfItemsInSection: desIndexPath.section)
            sectionPageControl.numberOfPages = itemCount / pageCount + 1
            sectionChange?(desIndexPath.section)
            currentSection = desIndexPath.section
        }
        
    }
}


//MARK: - <UICollectionViewDelegate>
extension XASectionPageView : UICollectionViewDelegate{
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        dealScrollDidEnd()
    
    }

    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate{
            dealScrollDidEnd()
        }
    }

    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
      
        pageViewDelegate?.pageView?(superview as! XAPageView, onSectionPageDidSelectItemAt: indexPath)
    }
//
    
}


//MARK: - <UICollectionViewDataSource>
extension XASectionPageView : UICollectionViewDataSource{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        guard let _ = superview as? XAPageView,
             let pageViewDataSource = pageViewDataSource else {
            return 0
        }
        let sections = pageViewDataSource.pageViewOnSectionPageNumOfSection?() ?? 0
        return sections
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       let nums =  pageViewDataSource!.pageView!(superview as! XAPageView, onSectionPageNumOfItemsInSection: section)
       return nums
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        return pageViewDataSource!.pageView!(superview as! XAPageView, onSectionPageCellForItemAt: indexPath)
    }
}

//MARK: - <XATitleViewDelegate>
extension XASectionPageView : XATitleViewDelegate{
    func titleView(_ titleView : XATitleView,selectedIndex : Int) ->Void{
        let sections =  pageViewDataSource?.pageViewOnSectionPageNumOfSection?() ?? 0
        if selectedIndex < sections{
            let indexPath = IndexPath(item: 0, section: selectedIndex)
            collectionView .scrollToItem(at: indexPath, at: .left, animated: false)
            //第0个item与collectionView左对齐之后,在滚动一个偏移距离
            collectionView.setContentOffset(CGPoint(x: collectionView.contentOffset.x -  sectionPageLayout.sectionInset.left, y: 0), animated: false)
            dealSubviewsStatus(sectionChange: nil)
        }
        
    }
    
}



